//
//  Common.m
//  iAPHD
//
//  Created by 曹兴星 on 13-6-9.
//  Copyright (c) 2013年 曹兴星. All rights reserved.
//

#import "Common.h"
#import <MessageUI/MFMessageComposeViewController.h>
#include <sys/socket.h> 
#include <sys/sysctl.h>
#include <net/if.h>
#include <net/if_dl.h>
#import "MBProgressController.h"

@implementation Common

/*==============================公用方法===========================*/

#pragma -mark 系统相关
//获取当前软件版本
+ (NSString *)getCurrentAppVersion {
    NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];
    // app版本
    NSString *app_Version = [infoDictionary objectForKey:@"CFBundleShortVersionString"];
    return app_Version;
}

//获取当前软件名称
+ (NSString *)getCurrentAppName {
    NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];
    // app名称
    NSString *app_Name = [infoDictionary objectForKey:@"CFBundleDisplayName"];
    return app_Name;
}

//拨打电话
+ (BOOL)makeCall:(NSString *)telno {
    if(!isiPhone){
        Alert(@"您的设备不是iPhone，不好拨打电话");
        return NO;
    }
    if(![Common isMobileNumber:telno]){
        Alert(@"电话号码不合法");
        return NO;
    }
    NSURL *phoneNumberURL = [NSURL URLWithString:[NSString stringWithFormat:@"telprompt://%@", telno]];
    [[UIApplication sharedApplication] openURL:phoneNumberURL];
    return YES;
}


//获取设备的mac地址
+ (NSString *)getMacAddress {
	int                    mib[6];
	size_t                 len;
	char                   *buf;
	unsigned char          *ptr;
	struct if_msghdr       *ifm;
	struct sockaddr_dl     *sdl;
	
	mib[0] = CTL_NET;
	mib[1] = AF_ROUTE;
	mib[2] = 0;
	mib[3] = AF_LINK;
	mib[4] = NET_RT_IFLIST;
	
	if ((mib[5] = if_nametoindex("en0")) == 0) {
		printf("Error: if_nametoindex error/n");
		return NULL;
	}
	
	if (sysctl(mib, 6, NULL, &len, NULL, 0) < 0) {
		printf("Error: sysctl, take 1/n");
		return NULL;
	}
	
	if ((buf = malloc(len)) == NULL) {
		printf("Could not allocate memory. error!/n");
		return NULL;
	}
	
	if (sysctl(mib, 6, buf, &len, NULL, 0) < 0) {
        free(buf);
		printf("Error: sysctl, take 2");
		return NULL;
	}
	
	ifm = (struct if_msghdr *)buf;
	sdl = (struct sockaddr_dl *)(ifm + 1);
	ptr = (unsigned char *)LLADDR(sdl);
	NSString *outstring = [NSString stringWithFormat:@"%02x%02x%02x%02x%02x%02x", *ptr, *(ptr+1), *(ptr+2), *(ptr+3), *(ptr+4), *(ptr+5)];
	free(buf);
	return [outstring uppercaseString];
}



//时间相关
#pragma -mark 时间相关
//获取系统当前时间
+ (NSString *)getCurrentTimeFormat:(NSString *)formatStr {
    /* YYYY-MM-dd hh:mm:ss
       YY-MM-dd-hh-mm-ss
     时间格式
     */
    NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
    [formatter setDateFormat:formatStr];
    NSString *ret = [formatter stringFromDate:[NSDate date]];
    return ret;
}

//根据时间戳转换成时间
+ (NSString *)timeIntervalSince1970:(NSTimeInterval)secs Format:(NSString*)formatStr {
	NSDate *date = [NSDate dateWithTimeIntervalSince1970:secs];
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
	[formatter setDateFormat:formatStr];
    NSString *ret = [formatter stringFromDate:date];
    return ret;
}

//String ====> Date  （字符串转时间）
+ (NSDate *)dateFromString:(NSString *)dateString
                  Formater:(NSString *)formater {
    NSDateFormatter *dateFormater = [[NSDateFormatter alloc] init];
    [dateFormater setDateFormat:formater];
    NSDate *date = [dateFormater dateFromString:dateString];
    return date;
}

//Date =====> String （时间转字符串）
+ (NSString *)stringFromDate:(NSDate *)date
                    Formater:(NSString *)formater {
    NSDateFormatter *dateFormater = [[NSDateFormatter alloc] init];
    [dateFormater setDateFormat:formater];
    NSString *dateString = [dateFormater stringFromDate:date];
    return dateString;
}

//距离现在的天、时、分、秒
+ (NSString *)compareCurrentTime:(NSTimeInterval) interval {
    if (interval < 0) interval *= -1.0;
    unsigned long timeInterval = interval / 1000.0;
    long daySec  = 60 * 60 * 24;
    long hourSec = 60 * 60;
    int tmpDay, tmpHour;
    NSMutableString *result = [NSMutableString string];
    if (timeInterval / daySec > 0) {
        tmpDay = timeInterval / daySec;
        [result appendFormat:@"%d天", tmpDay];
        if ((timeInterval % daySec) / hourSec > 0) {
            tmpHour = (timeInterval % daySec) / hourSec;
            [result appendFormat:@"%d时",tmpHour];
        }
    } else {
        if (timeInterval / hourSec > 0) {
            tmpHour = timeInterval / hourSec;
            if (timeInterval % hourSec == 0) {
                [result appendFormat:@"%d时", tmpHour];
            } else {
                [result appendFormat:@"%d.5时", tmpHour];
            }
        } else {
            [result appendString:@"0.5时"];
        }
    }
    return  result;
}

//正则匹配
#pragma -mark 正则匹配
//电话号码合法性检查
+ (BOOL)isMobileNumber:(NSString *)mobileNum {
    //入参检查
    NSRange range = [mobileNum rangeOfString:@"-"];
    if (range.location != NSNotFound) {
        [mobileNum stringByReplacingOccurrencesOfString:@"-" withString:@""];
    }
    /**
     * 手机号码
     * 移动：134[0-8],135,136,137,138,139,150,151,157,158,159,181,182,187,188
     * 联通：130,131,132,152,155,156,185,186
     * 电信：133,1349,153,180,189
     * 增加：14开头的号码
     */
    NSString * MOBILE = @"^1(3[0-9]|4[0-9]|5[0-35-9]|8[0125-9])\\d{8}$";
    
    /**
     10         * 中国移动：China Mobile
     11         * 134[0-8],135,136,137,138,139,150,151,157,158,159,182,187,188
     12         */
    NSString * CM = @"^1(34[0-8]|(3[5-9]|5[017-9]|8[278])\\d)\\d{7}$";
    
    /**
     15         * 中国联通：China Unicom
     16         * 130,131,132,152,155,156,185,186
     17         */
    NSString * CU = @"^1(3[0-2]|5[256]|8[56])\\d{8}$";
    
    /**
     20         * 中国电信：China Telecom
     21         * 133,1349,153,180,189
     22         */
    NSString * CT = @"^1((33|53|8[09])[0-9]|349)\\d{7}$";
    
    /**
     25         * 大陆地区固话及小灵通
     26         * 区号：010,020,021,022,023,024,025,027,028,029
     27         * 号码：七位或八位
     28         */
    NSString * PHS = @"^0(10|2[0-5789]|\\d{3})\\d{7,8}$";
    
    NSPredicate *regextestmobile = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", MOBILE];
    NSPredicate *regextestcm = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CM];
    NSPredicate *regextestcu = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CU];
    NSPredicate *regextestct = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CT];
    NSPredicate *regextestphs = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", PHS];
    
    if (([regextestmobile evaluateWithObject:mobileNum])|| ([regextestcm evaluateWithObject:mobileNum])|| ([regextestct evaluateWithObject:mobileNum])|| ([regextestcu evaluateWithObject:mobileNum]) || ([regextestphs evaluateWithObject:mobileNum])) {
        return YES;
    } else {
        return NO;
    }
}

//邮箱合法性
+ (BOOL)isEmail:(NSString *)emailAddress {
    NSString *emailRegex = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
    NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];
    return [emailTest evaluateWithObject:emailAddress];
}

+ (BOOL)isCharacter:(NSString *)characterNum {
    NSMutableCharacterSet *letterBase = [NSMutableCharacterSet letterCharacterSet];   //字母
    NSCharacterSet *decimalDigit = [NSCharacterSet decimalDigitCharacterSet];   //十进制数字
    [letterBase formUnionWithCharacterSet:decimalDigit];    //字母加十进制
    [letterBase invert];
    NSRange userNameRange = [characterNum rangeOfCharacterFromSet:letterBase];
    if (userNameRange.location != NSNotFound) {
        return YES;
    } else{
        return NO;
    }
}

//是否纯数字
+ (BOOL)isAllNum:(NSString *)string {
    if([Common isEmptyString:string]){
        return NO;
    }
    unichar c;
    for (int i = 0; i < string.length; i++) {
        c = [string characterAtIndex:i];
        if (!isdigit(c)) {
            return NO;
        }
    }
    return YES;
}


//加密解密
#pragma -mark 加密解密


//字符串处理
#pragma -mark 字符串处理
//过滤HTML标签
+ (NSString *)flattenHTML:(NSString *)html {
	if (!html) {
		return nil;
	}
    NSScanner *theScanner;
    NSString *text = nil;
    
    theScanner = [NSScanner scannerWithString:html];
    NSString *ret = [NSString stringWithString:html];
    
    while (![theScanner isAtEnd]) {
        // find start of tag
        [theScanner scanUpToString:@"<" intoString:NULL] ;
        // find end of tag
        [theScanner scanUpToString:@">" intoString:&text] ;
        // replace the found tag with a space
        //(you can filter multi-spaces out later if you wish)
        ret = [ret stringByReplacingOccurrencesOfString:[NSString stringWithFormat:@"%@>", text]
                                             withString:@" "];
        //过滤&nbsp;
        ret = [ret stringByReplacingOccurrencesOfString:@"&nbsp;"
                                             withString:@" "];
    }
    return ret;
}

//字符串为空检查
+ (BOOL)isEmptyString:(NSString *)sourceStr {
    if ((NSNull *)sourceStr == [NSNull null]) {
        return YES;
    }
    if ([sourceStr isEqualToString:@"null"]) {
        return YES;
    }
    if ([sourceStr isEqualToString:NullString]) {
        return YES;
    }
    if (sourceStr == nil) {
        return YES;
    }
    if (sourceStr == NULL) {
        return YES;
    }
       if (sourceStr.length == 0) {
        return YES;
    }
    return NO;
}

//UI相关
#pragma -mark UI相关
//去除UITableView多余分割线
+ (void)removeExtraCellLines:(UITableView *)tableView {
    UIView *view = [UIView new];
    view.backgroundColor = ClearColor;
    [tableView setTableFooterView:view];
}


//生成自己绘制的图片
+ (UIImage *)drawImageSize:(CGSize)size
                     Color:(UIColor *)color {
    UIGraphicsBeginImageContextWithOptions(size, 0, [UIScreen mainScreen].scale);
    [color set];
    UIRectFill(Frame(0, 0, size.width, size.height));
    UIImage *resImg = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return resImg;
}

//根据16进制显示颜色
+ (UIColor *)colorFromHexRGB:(NSString *)inColorString {
    UIColor *result = nil;
    unsigned int colorCode = 0;
    unsigned char redByte, greenByte, blueByte;
    if (![Common isEmptyString:inColorString]) {
        NSScanner *scanner = [NSScanner scannerWithString:inColorString];
        (void) [scanner scanHexInt:&colorCode]; // ignore error
    }
    redByte = (unsigned char) (colorCode >> 16);
    greenByte = (unsigned char) (colorCode >> 8);
    blueByte = (unsigned char) (colorCode); // masks off high bits
    result = [UIColor
              colorWithRed: (float)redByte / 0xff
                     green: (float)greenByte/ 0xff
                      blue: (float)blueByte / 0xff
                     alpha: 1.0];
    return result;
}

//改变图片大小
+(UIImage*)imageWithImage:(UIImage*)image scaledToSize:(CGSize)newSize {
    // Create a graphics image context
    UIGraphicsBeginImageContext(newSize);
    // Tell the old image to draw in this new context, with the desired
    // new size
    [image drawInRect:CGRectMake(0,0,newSize.width,newSize.height)];
    // Get the new image from the context
    UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
    // End the context
    UIGraphicsEndImageContext();
    // Return the new image.
    return newImage;
}
+ (UIBarButtonItem *)createBackBarButton:(NSString *)name
                                Selector:(void(^)())block {
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    btn.frame = CGRectMake(0, 0, 20, 20);
//    [btn handleControlEvent:UIControlEventTouchUpInside withBlock:block];
//    [btn setImage:Image(@"backBtnU.png")
//         forState:UIControlStateNormal];
//    [btn setImage:Image(@"backBtnS.png")
       //  forState:UIControlStateHighlighted];
    if (![Common isEmptyString:name]) {
        [btn setTitle:name
             forState:UIControlStateNormal];
        [btn setTitleColor:[UIColor whiteColor]
                  forState:UIControlStateNormal];
        [btn.titleLabel setFont:Font(16.0)];
        [btn sizeToFit];
    }
    UIBarButtonItem *barItem = [[UIBarButtonItem alloc] initWithCustomView:btn];
    return barItem;
}

+(NSString *)dictoJson:(NSDictionary *)dic
{
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dic options:(NSJSONWritingOptions)0
                                                     error:nil];
    NSString *tmpstr = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
   return [NSString stringWithFormat:@"[%@]",tmpstr];
}

+(NSString *)performEventstring:(NSInteger )hostid Metuod:(NSString *)method Value:(NSString *)value Events:(NSString *)events
{
    NSString *xml = [NSString stringWithFormat:@"\\\"<Message><Command Name='%@' Description='切屏'><Params><Param Name='%@' Value='%@'/><Param Name='Mthod' Value='%@' /></Params></Command></Message>\\\"",method,method,value,events];
    NSString *commend = [NSString stringWithFormat:@"{\"messageData\":\"%@}\",\"messageType\":8}",[NSString stringWithFormat:@"{\\\"hostId\\\":%ld,\\\"message\\\":%@",hostid,xml]];
    return commend;
}
+(NSString *)hostidtostring:(NSInteger )hostid Metuod:(NSString *)method
{
    NSString *xml = [NSString stringWithFormat:@"\\\"<Message><Command Name='%@' Description='切屏'><Params><Param Name='%@' Value='True'/></Params></Command></Message>\\\"",method,method];
    NSString *commend = [NSString stringWithFormat:@"{\"messageData\":\"%@}\",\"messageType\":8}",[NSString stringWithFormat:@"{\\\"hostId\\\":%ld,\\\"message\\\":%@",hostid,xml]];
    return commend;
}
+(NSString *)hostidtoFalsestring:(NSInteger )hostid Metuod:(NSString *)method
{
    NSString *xml = [NSString stringWithFormat:@"\\\"<Message><Command Name='%@' Description='切屏'><Params><Param Name='%@' Value='False'/></Params></Command></Message>\\\"",method,method];
    NSString *commend = [NSString stringWithFormat:@"{\"messageData\":\"%@}\",\"messageType\":8}",[NSString stringWithFormat:@"{\\\"hostId\\\":%ld,\\\"message\\\":%@",hostid,xml]];
    return commend;
}
+(NSString *)tcpDrawingstring:(NSInteger )hostid Metuod:(NSString *)method Param:(NSString *)param Type:(NSString *)type
{
    
 NSString *xml = [NSString stringWithFormat:@"\\\"<Message><Command Name='%@' Description='message'><Params><Param Name='HostId' Value='%ld'/><Param Name='%@' Value='%@'/></Params></Command></Message>\\\"",method,hostid,type,param];
NSString *commend = [NSString stringWithFormat:@"{\"messageData\":\"%@}\",\"messageType\":8}",[NSString stringWithFormat:@"{\\\"attachments\\\":[],\\\"hostId\\\":%ld,\\\"hosts\\\":[],\\\"message\\\":%@",hostid,xml]];
    return commend;
}

+(NSString *)tcpStartEnDevDrastring:(NSInteger )hostid Metuod:(NSString *)method
{
    NSString *xml = [NSString stringWithFormat:@"\\\"<Message><Command Name='%@' Description='message'><Params><Param Name='HostId' Value='%ld'/></Params></Command></Message>\\\"",method,hostid];
    NSString *commend = [NSString stringWithFormat:@"{\"messageData\":\"%@}\",\"messageType\":8}",[NSString stringWithFormat:@"{\\\"attachments\\\":[],\\\"hostId\\\":%ld,\\\"hosts\\\":[],\\\"message\\\":%@",hostid,xml]];
    return commend;
}
//发送point
+(NSString *)tcpDrawPonitstring:(NSInteger )hostid Metuod:(NSString *)method Fpoint:(CGPoint)fp Spoint:(CGPoint)sp Tpoint:(CGPoint)tp //Hpoint:(CGPoint)hp
//    Fpoint1:(CGPoint)fp1 Spoint1:(CGPoint)sp1 Tpoint1:(CGPoint)tp1 Hpoint1:(CGPoint)hp1
{
    NSString *xml = [NSString stringWithFormat:@"\\\"<Message><Command Name='%@' Description='message'><Params><Param Name='HostId' Value='%ld'/><Param Name='Points' Value='%f,%f %f,%f %f,%f'/></Params></Command></Message>\\\"",method,hostid,fp.x,fp.y,sp.x,sp.y,tp.x,tp.y];//,tp.x,tp.y,hp.x,hp.y];//,fp1.x,fp1.y,sp1.x,sp1.y,tp1.x,tp1.y,hp1.x,hp1.y];
    NSString *commend = [NSString stringWithFormat:@"{\"messageData\":\"%@}\",\"messageType\":8}",[NSString stringWithFormat:@"{\\\"attachments\\\":[],\\\"hostId\\\":%ld,\\\"hosts\\\":[],\\\"message\\\":%@",hostid,xml]];
    return commend;
}
+(NSString *)tcpDrawPonitSECstring:(NSInteger )hostid Metuod:(NSString *)method Fpoint:(CGPoint)fp Spoint:(CGPoint)sp Tpoint:(CGPoint)tp Hpoint:(CGPoint)hp
//    Fpoint1:(CGPoint)fp1 Spoint1:(CGPoint)sp1 Tpoint1:(CGPoint)tp1 Hpoint1:(CGPoint)hp1
{
    NSString *xml = [NSString stringWithFormat:@"\\\"<Message><Command Name='%@' Description='message'><Params><Param Name='HostId' Value='%ld'/><Param Name='Points' Value='%f,%f %f,%f %f,%f %f,%f'/></Params></Command></Message>\\\"",method,hostid,fp.x,fp.y,sp.x,sp.y,tp.x,tp.y,hp.x,hp.y];//,tp.x,tp.y,hp.x,hp.y];//,fp1.x,fp1.y,sp1.x,sp1.y,tp1.x,tp1.y,hp1.x,hp1.y];
    NSString *commend = [NSString stringWithFormat:@"{\"messageData\":\"%@}\",\"messageType\":8}",[NSString stringWithFormat:@"{\\\"attachments\\\":[],\\\"hostId\\\":%ld,\\\"hosts\\\":[],\\\"message\\\":%@",hostid,xml]];
    return commend;
}
//发送point begin
+(NSString *)tcpDrawPonitBEstring:(NSInteger )hostid Metuod:(NSString *)method Fpoint:(CGPoint)fp
{
    NSString *xml = [NSString stringWithFormat:@"\\\"<Message><Command Name='%@' Description='message'><Params><Param Name='HostId' Value='%ld'/><Param Name='Points' Value='%f,%f'/></Params></Command></Message>\\\"",method,hostid,fp.x,fp.y];
    NSString *commend = [NSString stringWithFormat:@"{\"messageData\":\"%@}\",\"messageType\":8}",[NSString stringWithFormat:@"{\\\"attachments\\\":[],\\\"hostId\\\":%ld,\\\"hosts\\\":[],\\\"message\\\":%@",hostid,xml]];
    return commend;
}
// x y 发送
+(NSString *)tcpDrawXYstring:(NSInteger )hostid Metuod:(NSString *)method X:(CGFloat)x Y:(CGFloat)y
{
    NSString *xml = [NSString stringWithFormat:@"\\\"<Message><Command Name='%@' Description='message'><Params><Param Name='HostId' Value='%ld'/><Param Name='X' Value='%f'/><Param Name='Y' Value='%f'/></Params></Command></Message>\\\"",method,hostid,x,y];
    NSString *commend = [NSString stringWithFormat:@"{\"messageData\":\"%@}\",\"messageType\":8}",[NSString stringWithFormat:@"{\\\"attachments\\\":[],\\\"hostId\\\":%ld,\\\"hosts\\\":[],\\\"message\\\":%@",hostid,xml]];
    return commend;
}

//关闭事件
+(NSString *)closeEvent:(NSInteger )hostid Metuod:(NSString *)method
{
    NSString *xml = [NSString stringWithFormat:@"\\\"<Message><Command Name='%@' Description='关闭'><Params><Param Name='Id' Value=''/></Params></Command></Message>\\\"",method];
    NSString *commend = [NSString stringWithFormat:@"{\"messageData\":\"%@}\",\"messageType\":8}",[NSString stringWithFormat:@"{\\\"hostId\\\":%ld,\\\"message\\\":%@",hostid,xml]];
    return commend;
}


//json 转 dic
+(NSArray *)jsontoArr:(NSString *)str
{
    NSString *strr = [str substringToIndex:str.length-2];
    NSString *strpp = [strr substringFromIndex:1];
    NSData *data = [strpp dataUsingEncoding:NSUTF8StringEncoding];
    id jsonObj = [NSJSONSerialization JSONObjectWithData:data options:
              NSJSONReadingMutableLeaves error:nil];
    return jsonObj;
}
+(NSDictionary *)jsontoArray:(NSString *)str
{
    NSData *data = [str dataUsingEncoding:NSUTF8StringEncoding];
    id jsonObj = [NSJSONSerialization JSONObjectWithData:data options:
                  NSJSONReadingMutableLeaves error:nil];
    return jsonObj;
}
#pragma -mark System相关
/*==============================System相关===========================*/

@end
